import React from 'react';
import { inject, observer } from 'mobx-react';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;

import { WeaErrorPage, WeaTools } from 'ecCom';
import {WeaTop,WeaTab,WeaRightMenu} from 'ecCom';
import {Button,Modal,Spin} from 'antd';
import {Condition} from './ListCondition';
import ModalSave from '../public/ModalSave'
import ShareModal from '../public/ShareModal'
import isEmpty from 'lodash/isEmpty'
import forEach from 'lodash/forEach'
const confirm = Modal.confirm;
import {routerShape} from 'react-router';
import * as API_HIS from '../apis/fnaReportBase'
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import FnaPermission from '../public/FnaPermission';

/**
 * 费用查询统计表
 */
@inject('costStore')
@observer
class Cost extends React.Component {
	static contextTypes = {
	    router: routerShape
	};
	
	constructor(props) {
		super(props);
	}

	componentWillMount() {
		const { costStore } = this.props;	
        const { resetData } = costStore;
        resetData();
	}

	componentDidMount() {
		//一些初始化请求
		const { costStore } = this.props;	
        const {initDatas,setRouter} = costStore;		
		
		let {router} = this.context;
        setRouter(router);
		initDatas();
		
	}
	
	componentWillReceiveProps(nextProps) {
		
	}
	shouldComponentUpdate(nextProps, nextState) {
		
		return true;
	}
	componentWillUnmount() {
		//组件卸载时一般清理一些状态

	}

	render() {
		
		const { costStore } = this.props;
		const {loadingSaveModal,showSearchAd,topTab,topTabCount,
			   searchParams,form,dataKey,tableStore,
			   loading,showModal,setShowModal,saveModelInfo,hasRight,
			   modalSaveParam,advHisSearchParam} = costStore;
		const {shareDataKey,shareModalParams,showShareModel,shareTableStore,setShowShareModel} = costStore;
		const {queryShareData} = costStore;
		const {clearformRp,formRp,conditionRp,getModalForm} = costStore;

		return (
			<div style={{height:'100%'}}>
			<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@owyymd`} spinning={loading}>
				{hasRight == 1 && <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@xt6q86`} datas={this.getRightMenu()} collectParams={{favname:getLabel(28111,'收藏'), favouritetype:5}} >
				<WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@9szh5q`}
					title={getLabel(82605,'费用查询统计表')}
					loading={loading}
					icon={<i className='icon-coms-Finance'/>}
					iconBgcolor='#f14a2d'
					buttons={this.getTopButton()}
					buttonSpace={10}
					showDropIcon={true}
					dropMenuDatas={this.getRightMenu()}
				>
				
				<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@quxwb7`}
				    buttons={[]}
					buttonsAd={this.getAdButtons()}
					searchType={searchParams.index==0?['advanced']:['base','advanced']}
					searchsBaseValue={searchParams.index==0?"":advHisSearchParam.nameQuery}//默认值
					setShowSearchAd={this.setShowSearchAd}
                    hideSearchAd={this.doHideSearchAd}
                    searchsAd={
                            <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@qkab1y`} listStore={costStore} onEnterSearch={this.enterSearch}/>
                    }
                    showSearchAd={showSearchAd}
                    datas={topTab}
                    keyParam="key"  //主键
                    selectedKey={searchParams.index}
                    counts={topTabCount}
                    onChange={this.switchTab}
                    onSearch={this.baseSearch}
                    advanceHeight={300}
				/>
		
				<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@gfiswq`} 
                    comsWeaTableStore={tableStore}
                	hasOrder={true}
                	needScroll={true} 
                	onOperatesClick={this.operator}
                	getColumns={this.getColumnsInfo}
                />

				</WeaTop>	
                {showModal && <ModalSave ecId={`${this && this.props && this.props.ecId || ''}_ModalSave@kjawhg`}
                 	showModal={showModal}
                 	closeModel={setShowModal}
                 	saveModelInfo={saveModelInfo}
                 	value={modalSaveParam}
                 	clearformRp={clearformRp}
                 	formRp={formRp}
                 	conditionRp={conditionRp}
                 	getModalForm={getModalForm}
                 	loading={loadingSaveModal}
                />}

                <ShareModal ecId={`${this && this.props && this.props.ecId || ''}_ShareModal@v0yu23`}	
					id = {shareModalParams.id}
					title = {shareModalParams.title}
					rptTypeName = {shareModalParams.rptTypeName}
					showShareModel= {showShareModel}
					setShowShareModel = {setShowShareModel}
					tableStore = {shareTableStore}
					dataKey = {shareDataKey}
					queryShareData = {queryShareData}
				/>
				</WeaRightMenu>}
				</Spin>
				{hasRight == 4 && <FnaPermission ecId={`${this && this.props && this.props.ecId || ''}_FnaPermission@57ascx`}/>}
			</div>
		)
	}

	doHideSearchAd = () => {
		this.props.costStore.setShowSearchAd(false);
    }
	
	setShowSearchAd = (bool) => {
		this.props.costStore.setShowSearchAd(bool);
	}

	queryDetailInfo(record){
		const {costStore} =  this.props;
		const { searchParams,parseStringToJson,setTabkey,saveGUID,
			doSearch,initInfo,setIsSearch,setSaveFlag } = costStore;
    	//解析查询参数到json对象
		let params = parseStringToJson(record.qryConds);
		params = Object.assign({},params,{
				qryFunctionType:1,
				rptViewType:0,
				_guid1:record.guid1,
				flag:true
		});
		setTabkey(0);
		searchParams.index = 0;//这个要放在查询数据的前面,不然后面不会准确查询
		saveGUID(record.guid1);//保存GUID
		doSearch(params);//查询数据
		initInfo(params);//高级搜索
		setIsSearch(true);//显示按钮
		setSaveFlag(true);//这是已经保存的
    }

	getColumnsInfo = (data) => {
		const {costStore} = this.props;
		const {tabKey,isSearch} = costStore;
		const that = this;
		if(tabKey == 1 && isSearch == false && !isEmpty(data)){
			data[1].render = (text, record, index) => {
				return (<a onClick={that.queryDetailInfo.bind(that,record)}>{text}</a>);
			} 
		}

		return data;
	}
	
	//右键菜单
	getRightMenu(){
		const { costStore } = this.props;
		const { dataKey,tableStore,searchParams,saveFlag,charFlag,isSearch } = costStore;
		let btns = [];
		const that = this;
		

		//当点击了搜索但是没有保存会出现保存查询结果
		if(!saveFlag&&isSearch){
			btns.push({
	            key:"2",
	    		icon: <i className='icon-coms-Preservation'/>,
	            content:getLabel(82508,'保存查询结果'),
	            onClick: () =>{
	               that.directSaveResult();
	            }
    		});
		}

		//只要点击了搜索都会出现导出Excel
		if(isSearch){
			btns.push({
	            key:"3",
	    		icon: <i className='icon-coms-export'/>,
	            content:getLabel(28343,'导出Excel'),
	            onClick: () =>{
	               that.exportExcel();
	            }
    		});
		}

		if(searchParams.index=='1'){
			btns.push({
				key:"batchDelete",
				icon: <i className='icon-coms-Batch-delete'/>,
				disabled:tableStore.selectedRowKeys.length>0?false:true,
				content:getLabel(32136,'批量删除'),
				onClick:this.batchDelete.bind(this)
			});
		}
		
		btns.push({
            key:"colSet",
    		icon: <i className='icon-coms-Custom'/>,
            content:getLabel(32535,'显示列定制'),
            onClick: () =>{
                tableStore.setColSetVisible(dataKey,true);
    		    tableStore.tableColSet(dataKey,true);
            }
    	});
		return btns;
	}

	//tab右侧按钮菜单
	getTopButton(){
		const { costStore } = this.props;
		const { searchParams,saveFlag,charFlag,isSearch,tableStore } = costStore;
		let btns=[];
		//当切换到第二个tab会出现批量删除
		if(searchParams.index=='1'){
			btns.push((<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wsnbqq@BatchDelete`} type="primary" onClick={this.batchDelete.bind(this)} disabled={tableStore.selectedRowKeys.length>0?false:true}>{getLabel(32136,'批量删除')}</Button>));
		}

		//当点击了搜索但是没有保存会出现保存查询结果
		if(!saveFlag&&isSearch){
			btns.push((<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5vmr9l@DirectSaveResult`} type="primary" onClick={this.directSaveResult.bind(this)}>{getLabel(82508,'保存查询结果')}</Button>));
		}

		//只要点击了搜索都会出现导出Excel
		if(isSearch){
			btns.push((<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qz1pi7@ExportExcel`} type="primary" onClick={this.exportExcel.bind(this)}>{getLabel(28343,'导出Excel')}</Button>));
		}
		return btns;
	}
	
	//直接保存查询结果
	directSaveResult() {
		const {costStore} = this.props;
		const {guid,setModalSaveParam,setShowModal} = costStore;
		let params = Object.assign({},{
			tbName:"",
			description:"",
			rptTypeName:'fanRptCost',
			_guid1:guid,
			id:''
		});
		setModalSaveParam(params);//保存需要保存的条件
		setShowModal(true);
	}

	//导出Excel
    exportExcel(){
   	    const { costStore } = this.props;
   	    const { guid } = costStore;
    	let url = "/api/fna/excel/exportCost?_guid1="+guid;
    	window.location.href = url;
    }
    
    //批量删除
    batchDelete(){
    	const { costStore } = this.props;
    	const { tableStore,historyDelete } = costStore;
    	const { selectedRowKeys } = tableStore;
    	let ids = "";
    	if(selectedRowKeys.length<=0){
    		Modal.warning({
			    title: getLabel(15172,'系统提示'),
			    content: getLabel(32568,'请选择要删除的记录!'),
			    okText: getLabel(826,'确定'),
			    onOk() {},
			  });
    	} else {
    		for(let id of selectedRowKeys){
    			ids += id + ","
    		}
    		ids = ids.substring(0,ids.lastIndexOf(","));
    		let params = Object.assign({},{
				operation:'delete',
				rptTypeName:'fanRptCost',
				id:ids
			});
			confirm({
				 title: getLabel(131329,'信息确认'),
    			 content: getLabel(15097,'确定要删除吗?'),
    			 okText: getLabel(826,'确定'),
    			 cancelText: getLabel(31129,'取消'),
    			 onOk() {
  				 	historyDelete(params);
    			 },
    			 onCancel() {}
			});	
    	}
    }

	//获取高级搜索的form底部的按钮
    getAdButtons() {
    	const {costStore} = this.props;
    	const {doSearch,setShowSearchAd,clearFormFields,searchParams,generGUID} = costStore;
		let buts;
    	if(searchParams.index=='0'){
			buts = [
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x0748z@Search`} type="primary" onClick={()=>{generGUID(this.showConfirm.bind(this));}}>{getLabel(197,'搜索')}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u4st7u@Reset`} type="ghost" onClick={()=>{clearFormFields(0);}}>{getLabel(2022,'重置')}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gp7nhi@Cancel`} type="ghost" onClick={()=>{setShowSearchAd(false)}}>{getLabel(31129,'取消')}</Button>)
			];
    	}else if(searchParams.index=='1'){
			buts = [
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0ajrqr@Search`} type="primary" onClick={()=>{doSearch();setShowSearchAd(false);}}>{getLabel(197,'搜索')}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zw7fka@Reset`} type="ghost" onClick={()=>{clearFormFields(1);}}>{getLabel(2022,'重置')}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oydtno@Cancel`} type="ghost" onClick={()=>{setShowSearchAd(false)}}>{getLabel(31129,'取消')}</Button>)
			];
    	}
        return buts;
    }

	/**
	* 高级搜索回车搜索
	*/
	enterSearch = () => {
		const {costStore} = this.props;
    	const {doSearch,setShowSearchAd,searchParams,generGUID} = costStore;
		if(searchParams.index=='0'){
			generGUID(this.showConfirm.bind(this));
		}else if(searchParams.index=='1'){
			doSearch();
			setShowSearchAd(false);
		}
	}

	
	showConfirm() {
		let that  = this;
		const {costStore} = this.props;
    	const {doSearch,setShowSearchAd,searchParams,
    		   setIsSearch,setSaveFlag} = costStore;
		confirm({
			className:'fnaConfirm',
		    title: getLabel(131329,'信息确认'),
		    content: getLabel(82522,'确定要生成报表么?'),
		    okText: getLabel(826,'确定'),
			cancelText: getLabel(31129,'取消'),
		    onOk() {
		      setIsSearch(true);//点击了高级搜索
		      setSaveFlag(false);//这个时候还未保存
		      that.doSearch();
		      setShowSearchAd(false);//高级搜索隐藏
		      
		    },
		    onCancel() {

		    },
		});
	}
	
	//获取表单数据查询
    doSearch(){
		const {costStore} = this.props;
		const {guid,form,saveTempData} = costStore;
		const searchParamsAd = form.getFormParams();
		searchParamsAd.rptViewType = 0;
		searchParamsAd.qryFunctionType = 1;
		searchParamsAd._guid1 = guid;

		//这里存在WeaTool的异步请求,所以只能在保存的action里面回调进行查询
    	saveTempData(searchParamsAd,()=>{
			this.getFnaLoading(searchParamsAd);
		});

    	//调用查询线程进度方法
    	// const hide = message.loading(getLabel(385366,'正在执行中...'), 0);
		// this.getFnaLoading(searchParamsAd,hide);
    }

    getFnaLoading(params,hide){
		const {costStore} = this.props;
		const { guid,doSearch,form,baseParams } = costStore;
		const searchParamsAd = form.getFormParams();
		const newParams = { ...baseParams, ...searchParamsAd, ...params };
		doSearch(newParams,true,this.showSave.bind(this))
		//this.showSave();

		// API_HIS.getFnaLoadingInfo({'guid':guid}).then(data =>{
		// 	if(data.flag){
		// 		// 异步手动移除
  		// 		setTimeout(hide,1000);
  		// 		if(data.result.flag){
		// 			doSearch(newParams)
  		// 			this.showSave();
  		// 		}else{
  		// 			alert(data.result.msg);
  		// 		}				
		// 	}else{
		// 		let hideNew = hide;			
		// 		/*if(data.infoStr != ""){
		// 			setTimeout(hide,1000);
		// 			hideNew = message.loading(data.infoStr, 0);
		// 		}*/				
		// 		setTimeout(this.getFnaLoading(params,hideNew),2000); 
		// 	}

		// });	

	}
	
	showSave() {
		const {costStore} = this.props;
		const {guid,form,setModalSaveParam,setShowModal} = costStore;
		confirm({
			className:'fnaConfirm',
		    title: getLabel(131329,'信息确认'),
		    content: getLabel(82525,'是否保存查询结果？'),
		    okText: getLabel(826,'确定'),
			cancelText: getLabel(31129,'取消'),
		    onOk() {
		    	let params = Object.assign({},{
		    		tbName:"",
					description:"",
					rptTypeName:'fanRptCost',
					_guid1:guid,
					id:''
				});
				setModalSaveParam(params);//保存需要保存的条件
				setShowModal(true);
		    },
		    onCancel() {
		    },
		});
	}
	
	switchTab = (tabKey) => {
        const {costStore} = this.props;
        const {topTab,searchParams} = costStore;
        const {setShowSearchAd,initInfo,historyInfo,
        	   doSearch,baseHisSearch,setIsSearch,
        	   setTabkey,clearFormFields,setAdvHisSearchParam} = costStore;
        searchParams.index = topTab[tabKey].key;
        if(tabKey == 0){//查询报表
        	setTabkey(0);
        	initInfo({flag:false});
        	let value = Object.assign({},{
				qryFunctionType:0,
				rptViewType:0
			});
			setAdvHisSearchParam({nameQuery:""});
		    doSearch(value);
        }else{//历史查询结果
        	setTabkey(1);
        	setIsSearch(false);//切换后将高级搜索标志还原
        	setShowSearchAd(false);
        	historyInfo({rptTypeName:'fanRptCost'});
        	baseHisSearch({rptTypeName:'fanRptCost'});
        	clearFormFields(0);
        	clearFormFields(1);
        }
    }
	
	//基础搜索
    baseSearch = (value) => {
    	const {costStore} = this.props;
    	const {formHis} = costStore;
    	let data = Object.assign({
    		nameQuery:value,
    		rptTypeName:'fanRptCost'
    	});
    	costStore.baseHisSearch(data);
    	formHis.updateFields({
			advQryName:{
				value: value
			}
		});
    }

    //操作判断按钮
	operator = (record,index,operate,flag) => {
		let id = record.id;
		const {costStore} = this.props;
		const {searchParams,doSearch,initInfo,parseStringToJson,
			   historyDelete,baseHisSearch,setModalSaveParam,
			   setShowModal,setIsSearch,saveGUID,setSaveFlag,
			   setTabkey} = costStore;
		if(flag=='0'){
			//解析查询参数到json对象
			let params = parseStringToJson(record.qryConds);
			params = Object.assign({},params,{
					qryFunctionType:1,
					rptViewType:0,
					_guid1:record.guid1,
					flag:true
			});
			setTabkey(0);
			searchParams.index = 0;//这个要放在查询数据的前面,不然后面不会准确查询
    		saveGUID(record.guid1);//保存GUID
    		doSearch(params);//查询数据
			initInfo(params);//高级搜索
			setIsSearch(true);//显示按钮
    		setSaveFlag(true);//这是已经保存的
		}else if(flag=='1'){
			let params = Object.assign({},{
				tbName:record.tbName,
				description:record.description,
				id:record.id,
				rptTypeName:'fanRptCost',
				_guid1:record.guid1
			});
			setModalSaveParam(params);//数据回显
			setShowModal(true);
		}else if(flag=='2'){
			const { costStore } = this.props;
			const {setShareModalVisible,setShowShareModel,queryShareData } = costStore;
			let params = Object.assign({},{
				id:record.id,
				title:record.tbName,
				rptTypeName:'fanRptCost',
			});

			queryShareData({fnaTmpTbLogId:record.id,rptTypeName:'fanRptCost'});

			setShareModalVisible(params);
			setShowShareModel(true);
		}else if(flag=='3'){
			let params = Object.assign({},{
				operation:'delete',
				rptTypeName:'fanRptCost',
				id:id
			});
			confirm({
				 title: getLabel(131329,'信息确认'),
    			 content: getLabel(15097,'确定要删除吗?'),
    			 okText: getLabel(826,'确定'),
				 cancelText: getLabel(31129,'取消'),
    			 onOk() {
  				 	historyDelete(params);
    			 },
    			 onCancel() {}
			});	
		}
	}
}


export default WeaTools.tryCatch(React,
	props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@95u7nc`} msg={ props.error ? props.error : getLabel(385218,'对不起,该页面异常,请联系管理员!')} />,
	{error: ""}
)(Cost);




